package com.example.demoapp.ui;

import android.os.Bundle;
import android.text.TextUtils;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.demoapp.R;
import com.example.demoapp.utils.Event;
import com.google.android.material.snackbar.Snackbar;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class MainActivity extends AppCompatActivity {

    MainActivityViewModel mainActivityViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainActivityViewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);

        RecyclerView recyclerView = findViewById(R.id.list);
        PostAdapter postAdapter = new PostAdapter();
        recyclerView.setAdapter(postAdapter);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL));

        SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.left);
        swipeRefreshLayout.setOnRefreshListener(() -> mainActivityViewModel.refresh());

        mainActivityViewModel.posts.observe(this, postAdapter::submitList);
        mainActivityViewModel.errorMsg.observe(this, stringEvent -> {
            String errorMsg = stringEvent.getIfNotHandled();
            if (!TextUtils.isEmpty(errorMsg)) {
                Snackbar.make(MainActivity.this, recyclerView, errorMsg, Snackbar.LENGTH_SHORT).show();
            }
        });
        mainActivityViewModel.refreshState.observe(this, swipeRefreshLayout::setRefreshing);

        mainActivityViewModel.refresh();
    }

}